/* Copyright 2008 Robert C. Brinson <rbrinson@gmail.com>
 * 
 * This file is part of PictureTagger.
 *
 * PictureTagger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * PictureTagger is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PictureTagger.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Drawing;

namespace PictureTagger.PictureTaggerUtility
{
	public class ImageUtility
	{
		private static ImageUtility utility = null;
		
		private ImageUtility()
		{
		}
		
		public static ImageUtility Utility
		{
			get
			{
				if(utility == null)
				{
					utility = new ImageUtility();
				}
				
				return utility;
			}
		}
		
		public static byte[] GenerateImageThumbnail(string fullFilePath)
		{
			byte[] thumbnailByte = null;
			
			if(System.IO.File.Exists(fullFilePath))
			{
				try
				{
					System.IO.MemoryStream pictureStream = new System.IO.MemoryStream();
					Image picture = Image.FromFile(fullFilePath);
					int width = (picture.Width > picture.Height) ? 145 : (int)((145d / picture.Height) * picture.Width);
					int height = (picture.Height > picture.Width) ? 145 : (int)((145d / picture.Width) * picture.Height);

					Image thumbnailPicture = picture.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Utility.ThumbnailCallback), IntPtr.Zero);
					
					thumbnailPicture.Save(pictureStream, System.Drawing.Imaging.ImageFormat.Jpeg);
					thumbnailByte = new byte[pictureStream.Length];
					pictureStream.Position = 0;
					pictureStream.Read(thumbnailByte, 0, (int)pictureStream.Length);
				}
				catch(OutOfMemoryException)
				{
					throw;
				}
				catch(Exception)
				{
					throw;
				}
			}

			return thumbnailByte;
		}
		
		public bool ThumbnailCallback()
		{
			return true;
		}
	}
}